package controllers

import (
	"cookbook/api/models"
	"fmt"
	"os/exec"

	"github.com/asdine/storm/q"

	"github.com/asdine/storm"

	"github.com/astaxie/beego"
)

var DB *storm.DB

type BaseController struct {
	beego.Controller
}

type MainController struct {
	BaseController
}

func (c *MainController) Get() {
	c.TplName = "index.html"
}

func (c *MainController) A更新() {
	cmd := exec.Command("git", "pull")
	err := cmd.Run()
	if err != nil {
		c.Fail(1, err)
		return
	}
	c.Success("更新成功")
}

func (c *BaseController) Fail(返回码 int, 数据 interface{}) {
	var msg string
	switch 数据.(type) {
	case string:
		msg = 数据.(string)
	default:
		msg = fmt.Sprint(数据)
	}
	c.Data["json"] = map[string]interface{}{"返回码": 返回码, "数据": msg}
	c.ServeJSON()
}

func (c *BaseController) Success(数据 interface{}) {
	c.Data["json"] = map[string]interface{}{"返回码": 0, "数据": 数据}
	c.ServeJSON()
}

func (c *BaseController) Page(数据, model interface{}, query storm.Query) {
	总数, err := query.Limit(-1).Skip(0).Count(model)
	if err != nil {
		c.Fail(2, err)
		return
	}
	c.Data["json"] = map[string]interface{}{"返回码": 0, "数据": 数据, "总数": 总数}
	c.ServeJSON()
}

func (c *BaseController) GetUser() (user models.M用户) {
	Token := c.GetString("Token")
	if Token != "" {
		err := DB.Select(q.Eq("Token", Token)).First(&user)
		if err != nil {
			beego.Info("GetUser", err)
		}
	}
	return user
}

func (c *BaseController) UnLogin() bool {
	Token := c.GetString("Token")
	if Token == "" {
		c.Fail(-1, "未登录,请先登录")
		return true
	}
	user := c.GetUser()
	unLogin := user.Id == 0
	if unLogin {
		c.Fail(-1, "Token已过期,请重新登录")
	}
	return unLogin
}
